package com.big.map.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.client.utils.JSONUtils;
import com.big.cmn.DictFeignClient;
import com.big.common.result.Result;
import com.big.common.utils.GetLatAndLngByBaidu;
import com.big.common.utils.JsonUtils;
import com.big.map.service.MapService;
import com.big.model.model.map.Cities;
import com.big.model.model.map.CitiesVo;
import com.big.model.model.map.Coordinate;
import com.big.model.model.order.MerchandiseOrder;
import com.big.model.model.patient.address.PatientAddress;
import com.big.order.OrderFeignClient;
import com.big.patient.PatientFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Service
@Slf4j
public class MapServiceImpl implements MapService {


    @Autowired
    OrderFeignClient orderFeignClient;


    @Autowired
    PatientFeignClient patientFeignClient;

    @Autowired
    DictFeignClient dictFeignClient;
    //创建读写锁对象
    private ReadWriteLock rwLock = new ReentrantReadWriteLock();

    @Value("${gps.key}")
    private String  key;

    @Value("${gps.contentType}")
    private String  contentType;

    @Value("${gps.charset}")
    private String  charset;

    @Value("${gps.origin}")
    private String  origin;

    @Value("${gps.destination}")
    private String  destination;

    @Value("${gps.url}")
    private String  url;

    @Value("${gps.extensions}")
    private String  extensions;


    @Value("${gps.output}")
    private String  output;


    /**
     * 查看城市经纬度
     * @param addr
     * @return
     * @throws IOException
     */
    public Object[] getCoordinate(String addr) throws IOException {
        String lng = null;//经度
        String lat = null;//纬度
        String address = null;
        try {
            address = java.net.URLEncoder.encode(addr, "UTF-8");
        }catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        String key = "f4ad4b6c46137f51a06f7195b0402d95";
        String url = String.format("http://api.map.baidu.com/geocoder?address=%s&output=json&key=%s", address, key);
        URL myURL = null;
        URLConnection httpsConn = null;
        try {
            myURL = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        InputStreamReader insr = null;
        BufferedReader br = null;
        try {
            httpsConn = (URLConnection) myURL.openConnection();// 不使用代理
            if (httpsConn != null) {
                insr = new InputStreamReader( httpsConn.getInputStream(), "UTF-8");
                br = new BufferedReader(insr);
                System.out.println(br);
                String data = null;
                int count = 1;
                while((data= br.readLine())!=null){
                    if(count==5){
                        lng = (String)data.subSequence(data.indexOf(":")+1, data.indexOf(","));//经度
                        count++;
                    }else if(count==6){
                        lat = data.substring(data.indexOf(":")+1);//纬度
                        count++;
                    }else{
                        count++;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(insr!=null){
                insr.close();
            }
            if(br!=null){
                br.close();
            }
        }
        return new Object[]{lng,lat};
    }

    /**
     * 坐标图
     * @return
     */
    @Override
    public List<double[]> coordinateInfosList(String oId) throws IOException {

        //查询订单
        GetLatAndLngByBaidu getLatAndLngByBaidu = new GetLatAndLngByBaidu();
        String address = this.address(oId);
        Object[] o = getLatAndLngByBaidu.getCoordinate(address);
        System.out.println(o[0]);//经度
        System.out.println(o[1]);//纬度

        origin = "117.290575,34.212667"; //开始
        destination = o[0]+","+o[1]; //始向

        //调用的api的接口地址
        String apiPath = url+"/v3/direction/driving?origin="+origin+"&destination="+destination+"&extensions="+extensions+"&output="+output+"&key="+key;
        BufferedReader in = null;
        StringBuffer result = null;
        try {
            URL url = new URL(apiPath);
            //打开和url之间的连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Content-Type", contentType);
            connection.setRequestProperty("Charset", charset);
            connection.connect();
            result = new StringBuffer();
            //读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            String result2 =  result.toString(); //返回json字符串
            //获取数据
            JSONObject jsonObject = JSON.parseObject(result2);
            String data = jsonObject.getString("route");

            JSONObject jsonObject2 = JSON.parseObject(data);
            String paths = jsonObject2.getString("paths");

            JSONArray objects = JSON.parseArray(paths);
            String steps=null;
            for (int i = 0; i < objects.size(); i++) {
                JSONObject jsonObjectlist = objects.getJSONObject(i);
                steps= jsonObjectlist.getString("steps");
            }
            List<Coordinate> coordinates = JsonUtils.jsonToList(steps, Coordinate.class);
            List<String>dae=new ArrayList<>();
            List<double[]>doubles=new ArrayList<>();
            //添加写锁
            rwLock.writeLock().lock();
            try {
            coordinates.forEach(item->{
                String[] split = item.getPolyline().split(";");
                for (int i = 0; i < split.length; i++) {
                    dae.add((split[i]));
                }
            });
            dae.forEach(item -> {
                String[] split = item.split(",");
                double ling=0;
                for (int i = 0; i < split.length; i++){
                    double[] doub =new double[2];
                    if(i==0){
                        doub[0] = Double.valueOf(split[i]);
                        ling=doub[0];
                    }
                    if(i==1){
                        doub[1] = Double.valueOf(split[i]);
                        doub[0] = ling;
                    }
                    if(doub[0] != 0.0 && doub[1] != 0.0){
                        doubles.add(doub);
                    }
                }
            });
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                //解锁写锁
                rwLock.writeLock().unlock();
            }
            return doubles;
        }catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 经过地区
     * @return
     */
    @Override
    public   List<CitiesVo>  toponymList(String oId) throws IOException {

        //查询订单
        GetLatAndLngByBaidu getLatAndLngByBaidu = new GetLatAndLngByBaidu();
        String address = this.address(oId);
        Object[] o = getLatAndLngByBaidu.getCoordinate(address);
        System.out.println(o[0]);//经度
        System.out.println(o[1]);//纬度

        origin = "117.290575,34.212667"; //开始
        destination = o[0]+","+o[1]; //始向
        //调用的api的接口地址
        String apiPath = url+"/v3/direction/driving?origin="+origin+"&destination="+destination+"&extensions="+extensions+"&output="+output+"&key="+key;
        BufferedReader in = null;
        StringBuffer result = null;
        try {
            URL url = new URL(apiPath);
            //打开和url之间的连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Content-Type", contentType);
            connection.setRequestProperty("Charset", charset);
            connection.connect();
            result = new StringBuffer();
            //读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            String result2 =  result.toString(); //返回json字符串
            //获取数据
            JSONObject jsonObject = JSON.parseObject(result2);
            String data = jsonObject.getString("route");

            JSONObject jsonObject2 = JSON.parseObject(data);
            String paths = jsonObject2.getString("paths");

            JSONArray objects = JSON.parseArray(paths);
            String steps=null;
            List<String>dae=new ArrayList<>();
            for (int i = 0; i < objects.size(); i++) {
                JSONObject jsonObjectlist = objects.getJSONObject(i);
                steps= jsonObjectlist.getString("steps");
            }
            List<Cities> coordinates = JsonUtils.jsonToList(steps, Cities.class);
            List<String> citiess=new ArrayList<>();
            coordinates.forEach(item -> {
                Cities cities = JsonUtils.JSONStringInfoTurnClass(JSON.toJSONString(item), Cities.class);
                citiess.add(cities.getCities());
            });
            List<CitiesVo> citiesadd=new ArrayList<>();
            citiess.forEach(item -> {
                List<CitiesVo> citiesVo = JSONObject.parseArray(item, CitiesVo.class);
                //空直接加入
                    citiesadd.add(citiesVo.get(0));
            });
            //添加写锁
            return citiesadd;
        }catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 根据经纬度获取城市名称
     * @param longitude
     * @param latitude
     * @return
     */
    @Override
    public  String  latitudeAndLongitudeAddress(String longitude, String latitude) {
        //lat 小  log  大
        //参数解释: 纬度,经度 采用高德API可参考高德文档https://lbs.amap.com/

        String urlString = url+"/v3/geocode/regeo?location="+latitude+","+longitude+"&extensions=base&batch=false&roadlevel=0&key="+key;
        String res = "";
        try {
            URL url = new URL(urlString);
            java.net.HttpURLConnection conn = (java.net.HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                res += line+"\n";
            }
            in.close();
            //解析结果
            JSONObject jsonObject = JSONObject.parseObject(res);
            log.info(jsonObject.toJSONString());
            JSONObject jsonObject1 = jsonObject.getJSONObject("regeocode");
            res =jsonObject1.getString("formatted_address");
        } catch (Exception e) {
            log.error("获取地址信息异常{}",e.getMessage());
            return null;
        }
        return res;
    }


    //数据字典code
    public  String address(String oId){
        System.out.println(oId);

        Long aLong = this.orderInfo(oId);
        PatientAddress patientAddress = patientFeignClient.addressInfo(aLong);
        //省
        String provinceName = dictFeignClient.getName(String.valueOf(patientAddress.getProvinceCode()));
        //市
        String cityName = dictFeignClient.getName(String.valueOf(patientAddress.getCityCode()));
        //区
        String districtName = dictFeignClient.getName(String.valueOf(patientAddress.getDistrictCode()));

        String add=provinceName+cityName+districtName+patientAddress.getAddress();

        return add;
    }

    //查询订单地图
    public Long orderInfo(String oId){
        Result order = orderFeignClient.findOrder(oId);
        System.out.println(order);
        MerchandiseOrder merchandiseOrder = JsonUtils.JSONStringInfoTurnClass(JSON.toJSONString(order.getData()), MerchandiseOrder.class);
        return merchandiseOrder.getAId();
    }




}
